package jp.reflexworks.gae.blogger;


import java.util.ConcurrentModificationException;
import java.util.logging.Logger;
import javax.jdo.JDOCanRetryException;
import javax.jdo.JDOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import jp.reflexworks.gae.blogger.model.Product;
import jp.reflexworks.gae.util.KeyUtils;
import jp.reflexworks.gae.util.PMF;


public class JdoUtils {

	
	Logger logger = Logger.getLogger(this.getClass().getName());

	// Utils
	KeyUtils keyUtils = new KeyUtils(Product.class);

	public static final int DEFAULT_PAGESIZE = 100;

	
	private static final String BR = System.getProperty("line.separator");

	public void insert(Product product) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		int NUM_RETRIES = 3;

		try {
			for (int r = 0; r < NUM_RETRIES; r++) {
				try {
					tx.begin();
					logger.info("tx begin.");

					
					
					
					
					
					
					
					
					
					logger.info("commit.");
					tx.commit();
					break;

				} catch (JDOCanRetryException e) {
					if (r == (NUM_RETRIES - 1)) {
						throw e;
					}
					logger.info("rollbacked.");
					try {
						tx.rollback();
					} catch (Throwable ee) {
					}
				} catch (JDOException e) {
					logger.info("JDOException:" + e.getMessage());
					throw e;
				} catch (ConcurrentModificationException e) {
					logger.info("ConcurrentModificationException:"
							+ e.getMessage());
					throw e;
				}
			}

		} finally {
			if (tx.isActive()) {
				logger.info("rollbacked.");
				try {
					tx.rollback();
				} catch (Throwable e) {
					
				}
			}
			logger.info("pm closed.");
			try {
				pm.close();
			} catch (Throwable e) {
				
			}
		}
	}

	private void debug(Object message) {
		//System.out.println("DEBUG " + this.getClass().getName() +  " :" + message);
		System.out.println(message);
	}

	
	
}
